package net;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatClientFrame extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTextArea textArea = new JTextArea();

	private JScrollPane scroll = new JScrollPane(textArea);

	private JTextField textField = new JTextField();

	private JButton btn = new JButton("发送");

	private JPanel panel = new JPanel();

	private Socket socket;

	public ChatClientFrame() throws Exception {
		add(scroll);
		panel.setLayout(new BorderLayout());
		panel.add(textField);
		panel.add(btn, BorderLayout.EAST);
		add(panel, BorderLayout.SOUTH);
		setSize(200, 300);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		

//		String s = JOptionPane.showInputDialog("请输入ip:port:昵称");
//		String[] arr = s.split(":");
//		socket = new Socket(arr[0], Integer.parseInt(arr[1]));
		socket = new Socket("localhost",8000);
		// 不能在此读取数据，阻塞在此，界面会无响应
		final SocketHandler h = new SocketHandler(socket,"he");
		new Thread(h).start();
		
		btn.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String s = textField.getText();
				if(null!=s&&!"".equals(s)){
					h.send(s);
					textField.setText("");
				}
			}});
		
		textField.addKeyListener(new KeyAdapter(){
			public void keyReleased(KeyEvent e) {
				int key = e.getKeyCode();
				if(key==KeyEvent.VK_ENTER){
					String s = textField.getText();
					if(null!=s&&!"".equals(s)){
						h.send(s);
						textField.setText("");
					}
				}
			}
		});
		
		
	}

	class SocketHandler implements Runnable {
		Socket s;
		String nickname;
		BufferedReader in;

		PrintWriter out;

		public SocketHandler(Socket s,String nickname) throws Exception {
			this.nickname= nickname;
			this.s = s;
			in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			out = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
		}

		public void send(String s){
//			out.println(nickname+"说：");
			out.println(s);
			out.flush();
		}
		
		public void run() {
			String line;
			try {
				while ((line = in.readLine()) != null) {
					textArea.append(line+"\n");
				}
			} catch (Exception e) {
				//断开
			}
			//断开
			textArea.append("已经断开");
		}
	}

	public static void main(String[] args) throws Exception {
		ChatClientFrame cc = new ChatClientFrame();

	}

}
